import { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import {
  BoxGeometry,
  Mesh,
  MeshNormalMaterial,
  PerspectiveCamera,
  Scene,
  WebGLRenderer,
} from 'three';

export default () => {
  const [container, setContainer] = useState<HTMLCanvasElement>();
  const scene = new Scene();
  const camera = new PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000,
  );

  const renderer = new WebGLRenderer();

  // 正方形
  const geometry = new BoxGeometry();
  const material = new MeshNormalMaterial();
  const cube = new Mesh(geometry, material);

  function animate() {
    requestAnimationFrame(animate);

    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
  }

  useEffect(() => {
    renderer.setSize(window.innerWidth / 2, window.innerHeight / 2);
    document.body.appendChild(renderer.domElement);
    setContainer(renderer.domElement);

    scene.add(cube);
    camera.position.z = 5;

    animate();

    // 组件卸载时,移除节点
    return () => {
      document.body.removeChild(renderer.domElement);
    };
  }, []);
  return container ? (
    ReactDOM.createPortal(
      <div style={{ position: 'fixed', top: '20px', left: '20px' }}>
        HelloWorld！我是一个可爱的旋转正方形
      </div>,
      container,
    )
  ) : (
    <div>HelloWorld ！ 什么都没有!</div>
  );
};
